package com.ganbo.ms.pool.pool;

import com.ganbo.ms.pool.pojo.Snapshot;
import com.ganbo.ms.pool.pojo.SnapshotExtend;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.AbandonedConfig;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 自定义对象池
 *
 * @author: GanBo
 * @date: 2023/5/5 10:29
 */
public class SnapshotExtendPool extends GenericObjectPool<SnapshotExtend> {

    public SnapshotExtendPool(PooledObjectFactory<SnapshotExtend> factory) {
        super(factory);
    }

    public SnapshotExtendPool(PooledObjectFactory<SnapshotExtend> factory, GenericObjectPoolConfig<SnapshotExtend> config) {
        super(factory, config);
    }

    public SnapshotExtendPool(PooledObjectFactory<SnapshotExtend> factory, GenericObjectPoolConfig<SnapshotExtend> config, AbandonedConfig abandonedConfig) {
        super(factory, config, abandonedConfig);
    }

    /**
     * 计数回收对象
     *
     * @param snapshot
     */
    public void myReturnObject(Snapshot snapshot) {
        SnapshotExtend snapshotExtend = (SnapshotExtend) snapshot;
        int refCount = snapshotExtend.getRefCount().decrementAndGet();
        if (refCount == 0) {
            snapshotExtend.getRefCount().set(snapshotExtend.getInitRefCount());
            super.returnObject(snapshotExtend); //回收
        }
    }
}

